#!/usr/bin/env python

import os
import sys
import colorama
import ConfigParser
import logging.config

import resource as r

class Meta(object):
    '''Meta class
    
    @author Julot <andy.julot@gmail.com>
    @since Sunday, January 15, 2012. 04:45 PM'''
    
    def __init__(self, **kw):
        self.name = r.string.app.name
        self.description = r.string.app.description
        self.long_description = r.string.app.longDescription
        self.download_url = 'http://192.168.2.1/software/%s/' % self.name
        self.version = '1.0.0.0'
        self.histories = {'0.0.0.0': '2012-03-15', self.version: '[Date]'}
        
        self.trademarks = 'As I pray, unlimited syntax works'
        self.copyright = 'Copyright 2012 Julot'
        self.company_name = 'Seraphim'
        s  = 'May you do good and not evil.\r\n'
        s += 'May you find forgiveness for yourself and forgive others.\r\n'
        s += 'May you share freely, never taking more than you give.'
        self.comments = s
        self.script = 'main.py'
        self.icon = os.path.join(os.getcwdu(), "resource", "icon", 'app.ico')
        self.icon_resources = [(1, self.icon)]
        self.dest_base = '..\\%s' % self.name
        self.author = 'Julot'
        self.author_email = 'andy.julot@gmail.com'
        self.maintainer = 'Julot'
        self.maintainer_email = 'andy.julot@gmail.com'
        self.logging_config = '%s.logging.conf' % self.name
        
        versions = self.version.split('.')
        stages = ('Alpha', 'Beta', 'Release Candidate', 'Public Release')
        if int(versions[2]) == 3:
            if int(versions[3]) == 0:
                version = '%s.%s' % (versions[0], versions[1])
            else:
                version = '%s.%s Revision %s' % (versions[0], versions[1],
                                                 versions[3])
        else:
            if int(versions[3]) == 0:
                version = '%s.%s %s' % (versions[0], versions[1],
                                        stages[int(versions[2])])
            else:
                version = '%s.%s %s %s' % (versions[0], versions[1],
                                           stages[int(versions[2])],
                                           versions[3])
        self.long_version = version
        
        self.__dict__.update(kw)

class Config(ConfigParser.ConfigParser):
    '''Config class
    
    @author Julot <andy.julot@gmail.com>
    @since Sunday, January 15, 2012. 04:48 PM'''
    
    def __init__(self, *args, **kwargs):
        ConfigParser.ConfigParser.__init__(self, *args, **kwargs)
        self.read('%s.conf' % Meta().name)

class App(object):
    '''App class
    
    @author Julot <andy.julot@gmail.com>
    @since Sunday, January 15, 2012. 05:05 PM'''
    
    def __init__(self):
        self.initLogging()
        logging.info('%s started.' % Meta().name)
        colorama.init(autoreset=True)
        self.greeting()
    
    def __del__(self):
        s = 'Good bye.'
        sys.stdout.write(colorama.Fore.YELLOW + colorama.Style.BRIGHT + s)
        colorama.deinit()
        logging.info('%s shut down.\n' % Meta().name)
    
    def greeting(self):
        meta = Meta()
        s = '%s - %s\n' % (meta.name, meta.description)
        sys.stdout.write(colorama.Fore.YELLOW + colorama.Style.BRIGHT + s)
        s = 'Version %s\n\n' % meta.long_version
        sys.stdout.write(colorama.Fore.YELLOW + colorama.Style.BRIGHT + s)
    
    def initLogging(self):
        meta = Meta()
        if not os.path.lexists('log'): os.mkdir('log')
        if not os.path.lexists(meta.logging_config): self._createLoggingConfig()
        logging.config.fileConfig(meta.logging_config)
    
    def _createLoggingConfig(self):
        config = ConfigParser.RawConfigParser()
        
        config.add_section('loggers')
        config.set('loggers', 'keys', 'root')
        
        config.add_section('logger_root')
        config.set('logger_root', 'handlers', 'debug,warning')
        config.set('logger_root', 'level', 'NOTSET')
        
        config.add_section('formatters')
        config.set('formatters', 'keys', 'simple,complex')
        
        config.add_section('formatter_simple')
        s = '[%(asctime)s] [%(levelname)s] %(message)s'
        config.set('formatter_simple', 'format', s)
        
        config.add_section('formatter_complex')
        s = '[%(asctime)s] [%(levelname)s] [%(module)s : '
        s += '%(lineno)d] %(message)s'
        config.set('formatter_complex', 'format', s)
        
        config.add_section('handlers')
        config.set('handlers', 'keys', 'debug,warning')
        
        config.add_section('handler_debug')
        config.set('handler_debug', 'class', 'handlers.RotatingFileHandler')
        config.set('handler_debug', 'maxBytes', '1024')
        config.set('handler_debug', 'backupCount', '30')
        config.set('handler_debug', 'formatter', 'complex')
        config.set('handler_debug', 'level', 'DEBUG')
        s = "(os.path.join('log', 'debug.log'),)"
        config.set('handler_debug', 'args', s)
        
        config.add_section('handler_warning')
        config.set('handler_warning', 'class', 'handlers.RotatingFileHandler')
        config.set('handler_warning', 'maxBytes', '1024')
        config.set('handler_warning', 'backupCount', '30')
        config.set('handler_warning', 'formatter', 'simple')
        config.set('handler_warning', 'level', 'WARNING')
        s = "(os.path.join('log', 'warning.log'),)"
        config.set('handler_warning', 'args', s)
        
        with open(Meta().logging_config, 'wb') as configFile:
            config.write(configFile)
    